package com.adz.robotdemo;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.adz.robotdemo.adapter.ChatMessageAdapter;
import com.adz.robotdemo.bean.ChatMessage;
import com.adz.robotdemo.utils.Answer;
import com.adz.robotdemo.utils.AsyncHandler;
import com.adz.robotdemo.utils.MySQLiteHelper;
import com.adz.robotdemo.utils.Robot;
import com.adz.robotdemo.utils.RobotDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends Activity {
    /**
     * 展示消息的listview
     */
    private ListView mChatView;
    /**
     * 文本域
     */
    private EditText mMsg;
    /**
     * 存储聊天消息
     */
    private List<ChatMessage> mDatas = new ArrayList<ChatMessage>();
    /**
     * 适配器
     */
    private ChatMessageAdapter mAdapter;
    Robot robot = new Robot("593641dc0e0000b652a16670");
    /**
     * 定义HTML标签的正则表达式
     */
    private static final String REGEX_HTML = "<[^>]+>";
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            ChatMessage from = (ChatMessage) msg.obj;
            mDatas.add(from);
            mAdapter.notifyDataSetChanged();
            mChatView.setSelection(mDatas.size() - 1);
        }
    };
    RobotDialog robotDialog;
    TextView tv;

    MySQLiteHelper mySQLiteHelper;
    ProgressBar proBar;
    public static final String CREATE_CHATMSG = "create table msg1 ("
            + "id integer primary key autoincrement, "
            + "msg text, "
            + "date text, "
            + "tag integer)";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main_chatting);
        robotDialog = new RobotDialog(this);
        //robotDialog.initDialog();
        initView();
        robotDialog.setItemClick(new RobotDialog.ItemClick() {
            @Override
            public void onItemClick(String question) {
                setMsg(question);
                robotDialog.dismiss();
            }
        });
        mAdapter = new ChatMessageAdapter(this, mDatas);
        mChatView.setAdapter(mAdapter);
        tv = (TextView) findViewById(R.id.tv_question);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                robotDialog.initDialog();
            }
        });
        initQuestion();
        mySQLiteHelper=new MySQLiteHelper(this,"chatmsg",null,1);
        SQLiteDatabase db = mySQLiteHelper.getReadableDatabase();
//        db.execSQL(CREATE_CHATMSG);
        hisMsg(true,0,5);
    }

    private void initView() {
        proBar= (ProgressBar) findViewById(R.id.pro_bar);
        mChatView = (ListView) findViewById(R.id.id_chat_listView);
        mMsg = (EditText) findViewById(R.id.id_chat_msg);
        mDatas.add(new ChatMessage(ChatMessage.Type.INPUT, "天真可爱、机智聪慧、善良勇敢智能机器人时刻准备为您服务。如果没有查询到您想要的问题，请点击下方“人工客服”接入人工（8:00-22:00）为您服务"));

        mChatView.setOnScrollListener(new AbsListView.OnScrollListener() {
            private int firstItem;
            boolean tag=true;
            int page1=5;
            int page2=10;
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
                    //如果拉到顶端读取更多消息
                    proBar.setVisibility(View.VISIBLE);
                    if (hisMsg(tag,page1,page2)==0){
                        tag=false;
                    }
                    page1+=5;
                    page2+=5;
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                firstItem = i;
            }
        });
    }

    private void initQuestion() {
        ChatMessage from = new ChatMessage();
        from.setMsg("请用一句话描述您的问题，例如:个体用户如何填写公司名，或点击右上角常见问题。");
        from.setType(ChatMessage.Type.INPUT);
        from.setDate(new Date());
        Message message = Message.obtain();
        message.obj = from;
        mHandler.sendMessage(message);
    }

    public void sendMessage(View view) {
        final String msg = mMsg.getText().toString();
        if (TextUtils.isEmpty(msg)) {
            Toast.makeText(this, "您还没有填写信息...", Toast.LENGTH_SHORT).show();
            return;
        }
        setMsg(msg);
    }

    public void setMsg(String question) {
        ChatMessage to = new ChatMessage(ChatMessage.Type.OUTPUT, question);
        to.setDate(new Date());
        mDatas.add(to);
        InsertCity(to);
        mAdapter.notifyDataSetChanged();
        mChatView.setSelection(mDatas.size() - 1);

        mMsg.setText("");

        // 关闭软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // 得到InputMethodManager的实例
        if (imm.isActive()) {
            // 如果开启
//            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
//                    InputMethodManager.HIDE_NOT_ALWAYS);
            // 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0); //强制隐藏键盘
        }



        robot.getAnswer(question, new AsyncHandler<Answer>() {
            @Override
            public void onComplete(final Answer result) {
                // 过滤html标签
                Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
                Matcher m_html = p_html.matcher(result.answer);
                result.answer = m_html.replaceAll("");
                ChatMessage from = new ChatMessage();
                from.setMsg(result.answer);
                from.setType(ChatMessage.Type.INPUT);
                from.setDate(new Date());
                Message message = Message.obtain();
                message.obj = from;
                mHandler.sendMessage(message);
                InsertCity(from);
            }
        });
    }
    int tag;
    public void InsertCity(ChatMessage from) {
        SQLiteDatabase db = mySQLiteHelper.getReadableDatabase();
        if (from.getType() == ChatMessage.Type.INPUT){
            tag=1;
        }else{
            tag=2;
        }
        db.execSQL("insert into msg(msg, date, tag) values('" + from.getMsg() + "', '"
                + from.getDateStr() + "', " + tag +")");
        db.close();
    }

    private int hisMsg(boolean tag,int page1,int pag2) {
        SQLiteDatabase db = mySQLiteHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "select * from msg order by id desc limit "+page1+" , 5" , null);
        int newMsgNum = 0;
        while (cursor.moveToNext()&&tag) {
            ++newMsgNum;
            ChatMessage from = new ChatMessage();
            from.setMsg(cursor.getString(1));
            from.setDateStr(cursor.getString(2));
            if (cursor.getInt(3)==1) {
                from.setType(ChatMessage.Type.INPUT);
            }else {
                from.setType(ChatMessage.Type.OUTPUT);
            }
            mDatas.add(0,from);
        }
        mAdapter.notifyDataSetChanged();
        mChatView.setSelection(newMsgNum);
        proBar.setVisibility(View.GONE);
        if (allCaseNum(db)<=pag2) {
            cursor.close();
            db.close();
            return 0;
        }
        return -1;
    }

    /**
     * 查询数据库中的总条数.
     * @return
     */
    public long allCaseNum( SQLiteDatabase db ){
        String sql = "select count(*) from msg";
        Cursor cursor = db.rawQuery(sql, null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();
        return count;
    }
}
